import com.sun.deploy.perf.PerfRollup;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: SEKI TOMOKI
 * Date: 2023-08-30
 * Time: 21:30
 */

class Money implements Cloneable{
    public double m = 19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Person implements Cloneable{
    public String name;
    public int age;

    public Money money = new Money();

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    //这是浅拷贝需要被调用的clone方法
    /*@Override
    protected Object clone() throws CloneNotSupportedException {
        //这里只克隆了person1,没有克隆money
        return super.clone();
    }*/

    //这是深拷贝需要被调用的clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();
        //把this指向对象的 money所指向的对象再克隆一份
        tmp.money = (Money) money.clone();//与(Money) this.money.clone()一样
        return tmp;
    }
}
public class Test {

    //浅拷贝的例子
    public static void main2(String[] args) throws CloneNotSupportedException{
        //throws CloneNotSupportedException的意思是可能会抛出异常，这个异常叫做 不支持克隆异常,
        // 这是一个编译时期的异常，意思是要把异常处理掉，才能不报错。

        Person person1 = new Person("zhangsan",18);
        //通过调用Person类中重写的clone方法 访问Object类当中的clone方法
        //因为重写的clone方法的 返回类型为Object类型，
        //把Object类型 赋值给 Person类型时需要进行向下转型。
        Person person2 = (Person) person1.clone();
        System.out.println("person1 " + person1.money.m);//19.9
        System.out.println("person2 " + person2.money.m);//19.9
        System.out.println("==================");

        person1.money.m = 99.9;
        System.out.println("person1 " + person1.money.m);//99.9
        System.out.println("person2 " + person2.money.m);//99.9
    }

    //深拷贝的例子
    public static void main(String[] args) throws CloneNotSupportedException{
        Person person1 = new Person("zhangsan",18);
        //让person2接收tmp的值，然后tmp被回收了
        Person person2 = (Person) person1.clone();
        System.out.println("person1 " + person1.money.m);//19.9
        System.out.println("person2 " + person2.money.m);//19.9
        System.out.println("==================");

        person1.money.m = 299.9;
        System.out.println("person1 " + person1.money.m);//299.9
        System.out.println("person2 " + person2.money.m);//19.9
    }
}
